﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using App.Utilities.Web.Handlers;
using System.Data;
using CRMBiz;
using Newtonsoft.Json;
using System.Globalization;
using CRMFramework;
using CRMWeb.Utilities.Context;
using System.Text;

namespace CRMWeb.WebServices
{
    /// <summary>
    /// Summary description for DuplicateContactDetective
    /// </summary>
    public class DuplicateContactDetective : BaseHandler
    {

        public override void OnMethodInvoke(OnMethodInvokeArgs e)
        {
            context.Response.Cache.SetCacheability(HttpCacheability.ServerAndNoCache);
            context.Response.Cache.SetExpires(DateTime.MinValue);
            context.Response.Cache.SetNoStore();
            SetResponseContentType(ResponseContentTypes.HTML);
        }

        public override void AfterMethodInvoke(object result)
        {
            base.AfterMethodInvoke(result);
        }

        public void GetDuplicateContactAll(string searchfield)
        {
            try
            {
                var pageIndex = string.IsNullOrEmpty(context.Request["page"]) ? 1 : int.Parse(context.Request["page"]);
                var pageSize = string.IsNullOrEmpty(context.Request["rows"]) ? 10 : int.Parse(context.Request["rows"]);
                DataSet ds = DuplicateContactHandler.SelectDuplicateContact(pageIndex, pageSize, searchfield);
                var total = (ds.Tables[0].Rows.Count > 0) ? Convert.ToInt32(ds.Tables[0].Rows[0]["Total"]) : 0;
                string strJson = JsonConvert.SerializeObject(ds.Tables[0]);
                strJson = "{\"total\":\"" + total.ToString() + "\",\"rows\":" + strJson + "}";

                context.Response.Write(strJson);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex, CMSContext.CurrentUser.MemberName);
            }
        }

        public void GetDuplicatedContactID(string field, string value)
        {
            try
            {
                DataSet ds = DuplicateContactHandler.GetDuplicatClients(field, value);
                string strJson = JsonConvert.SerializeObject(ds.Tables[0]);
                context.Response.Write(strJson);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex, CMSContext.CurrentUser.MemberName);
            }
        }
        // This Method is called from ContactProfile sor Remove Single Client 
        public void RemoveDuplicateContact(int CurrentContactID, int DupWithContactID, string hOperator)
        {
            bool flag = false;
            try
            {
                flag = DuplicateContactHandler.RemoveDuplicateClient(CurrentContactID, DupWithContactID, hOperator);
                context.Response.Write(flag);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex, CMSContext.CurrentUser.MemberName);
                context.Response.Write(flag);
            }
        }

        public void PrepareDataGrid(int ContactID, string FirstName, string SurName, string DateBirth)
        {
            bool matched = false;
            var option = new StringBuilder();
            List<int> unmatchedRow = new List<int>();
            var datagrid = new StringBuilder("<table id=\"dgCompareDuplicate\"  style=\"width: auto; height: 350px;\">");
            try
            {
                if (!string.IsNullOrEmpty(FirstName))
                    FirstName = FirstName.Substring(0, 1);
                DataTable dt = DuplicateContactHandler.CompareDuplicateContact(ContactID, FirstName, SurName, DateBirth);
                bool[,] matchedCell = new bool[dt.Rows.Count, dt.Columns.Count];
                if (dt.Columns.Count > 20)
                {
                    context.Response.Write("0");
                    return;
                }
                if (dt.Columns.Count > 2)
                {
                    dt.Columns.Add("Compare");
                    for (int row = 0; row <= 11; row++)
                    {
                        for (int col = 1; col < dt.Columns.Count - 2; col++)
                        {
                            string str1 = dt.Rows[row][col].ToString().Trim();
                            string str2 = dt.Rows[row][col + 1].ToString().Trim();
                            str1 = str1.ToLower();
                            str2 = str2.ToLower();
                            if (str1.Equals(str2))
                            {
                                matched = true;
                                continue;
                            }
                            else
                            {
                                matched = false;
                                break;
                            }
                        }
                        if (matched == true)
                            dt.Rows[row]["Compare"] = 1;
                        else if (matched == false)
                        {
                            dt.Rows[row]["Compare"] = 0;
                            unmatchedRow.Add(row);
                            // Set Green Color where value matched
                            var CurrRow = string.Join(",", dt.Rows[row].ItemArray);
                            string[] rowArray = CurrRow.Split(',');
                            for (int i = 1; i < rowArray.Length - 1; i++)
                            {
                                for (int j = i + 1; j < rowArray.Length; j++)
                                {
                                    if (string.IsNullOrEmpty(rowArray[i]) || string.IsNullOrEmpty(rowArray[j]))
                                        continue;
                                    else
                                    {
                                        if (rowArray[i].Equals(rowArray[j]))
                                        {
                                            matchedCell[row, i] = true;
                                            matchedCell[row, j] = true;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                // Draw Datagrid Columns Header
                datagrid.Append("<th><td style=\"width:100px;text-align:center;font-family:cambira\"></td>");
                for (int x = 1; x < dt.Columns.Count; x++)
                {
                    if (dt.Columns[x].ColumnName.Equals(ContactID.ToString()))
                        datagrid.Append("<td style=\"width:150px;height:30px;text-align:center\"><lable id=\"lbl" + ContactID + "\" style=\"font-family:arial;font-size:medium;color:maroon\"> <b> Current Client </b> </lable> </td> ");
                    else if (dt.Columns[x].ColumnName == "Compare")
                        datagrid.AppendFormat("<td style=\"width:80px;height:30px;text-align:center\"><lable id=\"lbl{0} \" style=\"font-family:arial;font-size:medium\"><b> {0} </b> </lable> </td>", dt.Columns[x].ColumnName);
                    else
                        datagrid.AppendFormat("<td style=\"width:150px;height:30px;text-align:center\"><lable id=\"lbl{0}\" style=\"font-family:arial;font-size:medium\"><b> Client ID: {0} </b> </lable> </td>", dt.Columns[x].ColumnName);
                }
                datagrid.Append("</th>");
                for (int row = 0; row < dt.Rows.Count; row++)
                {
                    datagrid.Append("<tr>");
                    for (int col = 0; col < dt.Columns.Count; col++)
                    {
                        if (col == 0)
                        {
                            switch (row)
                            {
                                case 0:
                                    datagrid.AppendFormat("<td rowspan=\"12\" style=\"width:100px;color:maroon;text-align:center;font-family:verdana;font-size:14px\"> Client Profile </td> <td style=\"width:200px;text-align:left;font-family:cambira\"> <b> {0} </b> </td>", dt.Rows[row][col]);
                                    break;
                                case 12:
                                    datagrid.AppendFormat("<td rowspan=\"5\" style=\"width:100px;color:maroon;text-align:center;font-family:verdana;font-size:14px\"> Application Profile </td> <td style=\"width:200px;text-align:left;font-family:cambira\"> <b> {0} </b> </td>", dt.Rows[row][col]);
                                    break;
                                case 17:
                                    datagrid.AppendFormat("<td rowspan=\"4\" style=\"width:100px;color:maroon;text-align:center;font-family:verdana;font-size:14px\">   </td> <td style=\"width:200px;text-align:left;font-family:cambira\"> <b> {0} </b> </td>", dt.Rows[row][col]);
                                    break;
                                case 21:
                                    datagrid.AppendFormat("<td rowspan=\"2\" style=\"width:100px;color:maroon;text-align:center;font-family:verdana;font-size:14px\"> Action </td> <td style=\"width:200px;text-align:left;font-family:cambira\"> <b> {0} </b> </td>", dt.Rows[row][col]);
                                    break;
                                default:
                                    datagrid.AppendFormat("<td style=\"width:100px;text-align:left;font-family:cambira;font-size:12px\"> <b> {0} </b> </td>", dt.Rows[row][col]);
                                    break;
                            }
                        }
                        else
                        {
                            if (row < 12)
                            {
                                if (dt.Columns[col].ColumnName == "Compare")
                                {
                                    if ((dt.Rows[row][col].ToString() == "0"))
                                        datagrid.Append("<td style=\"width:70px;text-align:center\"><img src=\"../../Media/cancel.png\" style=\" width:auto;height:auto\"></td>");
                                    else if (dt.Rows[row][dt.Columns.Count - 1].ToString() == "1")
                                        datagrid.Append("<td style=\"width:70px;text-align:center\"><img src=\"../../Media/ok.png\" style=\" width:auto;height:auto\"></td></td>");
                                }
                                else
                                {
                                    if (unmatchedRow.Contains(row))
                                    {
                                        if (matchedCell[row, col] == true)
                                            datagrid.AppendFormat("<td style=\"width:150px;text-align:left;background-color:lightgreen\"> {0} </td>", dt.Rows[row][col]);
                                        else
                                            datagrid.AppendFormat("<td style=\"width:150px;text-align:left;background-color:pink\"> {0} </td>", dt.Rows[row][col]);
                                    }
                                    else
                                        datagrid.AppendFormat("<td style=\"width:150px;text-align:left\"> {0} </td>", dt.Rows[row][col]);
                                }
                            }
                            else if (row >= 12 && col < dt.Columns.Count - 1)
                            {
                                switch (row)
                                {
                                    case 12:
                                        {
                                            string strcomesfrom = string.Empty;
                                            int appFormId = Convert.ToInt32(dt.Rows[row][col].ToString());
                                            if (appFormId > 0)
                                            {
                                                strcomesfrom = DBhelper.ExecuteScalar("SELECT IFNULL(`comesfrom`,'') AS comesfrom FROM crm_application WHERE app_id=(SELECT app_id FROM crm_applicationcontact WHERE `ContactID`=" + dt.Columns[col].ColumnName + " AND deletedFlag=0) ");
                                            }

                                            datagrid.AppendFormat("<td style=\"width:150px;text-align:center\"> <a href=\"#\" onclick=\"openApplicationForm('{0}','{1}')\" > FormID:{2}  </a> </td>", appFormId, strcomesfrom, appFormId);
                                            break;
                                        }
                                    case 13:
                                        datagrid.AppendFormat("<td style=\"width:150px;text-align:left\"> {0} </td>", dt.Rows[row][col]);
                                        break;
                                    case 14:
                                        datagrid.AppendFormat("<td style=\"width:150px;text-align:left;background-color:#12cbe5\"> <b> {0} </b></td>", dt.Rows[row][col]);
                                        break;
                                    case 15:
                                        {
                                            option = new StringBuilder();
                                            DataSet ds = ApplicationContactHandler.GetApplicationForClient(Convert.ToInt32(dt.Columns[col].ColumnName));
                                            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                                            {
                                                option.Append("<option value=\" " + ds.Tables[0].Rows[i]["app_id"] + "\">" + ds.Tables[0].Rows[i]["app_id"] + "</option>");
                                            }
                                            datagrid.Append("<td style=\"width:150px;text-align:center\"><select id=\"cmbViewApp" + dt.Columns[col].ColumnName + "\" onchange=\" getAppData('")
                                                .Append(dt.Columns[col].ColumnName + "')\" > " + option.ToString() + " </select> <a href=\"#\" onclick=\"ViewApp('" + dt.Columns[col].ColumnName + "')\" >View </a></td>");
                                            break;
                                        }

                                    case 16:
                                        datagrid.AppendFormat("<td style=\"width:150px;text-align:left\"><lable id=\"lblloanAmt{0}\" ></lable> </td>", dt.Columns[col].ColumnName);
                                        break;
                                    case 17:
                                        datagrid.AppendFormat("<td style=\"width:150px;text-align:left\"><lable id=\"lblDate{0}\" ></lable> </td>", dt.Columns[col].ColumnName);
                                        break;
                                    case 18:
                                        datagrid.AppendFormat("<td style=\"width:150px;text-align:center\"><lable id=\"lblSecurity{0}\" ></lable> </td>", dt.Columns[col].ColumnName);
                                        break;
                                    case 19:
                                        datagrid.AppendFormat("<td style=\"width:150px;text-align:left;background-color:#12cbe5\"> <b> {0} </b></td>", dt.Rows[row][col]);
                                        break;
                                    case 20:
                                        datagrid.Append("<td style=\"width:150px;text-align:center\">  <select id=\"cmbgrp" + dt.Columns[col].ColumnName + "\" style=\"width: 50px\">")
                                                        .Append("<option value=\"1\">1</option><option value=\"2\">2</option> <option value=\"3\">3</option>")
                                                        .Append("<option value=\"4\">4</option><option value=\"5\">5</option></select></td>");
                                        break;
                                    case 21:
                                        datagrid.Append("<td style=\"width:150px;text-align:center\">  <select id=\"cmbClientAction" + dt.Columns[col].ColumnName + "\" ")
                                                        .Append(" style=\"width: 70px\"> <option value=\"Keep\">Keep</option><option value=\"Delete\">Delete</option></select></td>");
                                        break;
                                    case 22:
                                        datagrid.AppendFormat("<td style=\"width:150px;text-align:center\"> <select class=\"easyui-combogrid\" style=\"width:100px\" id=\"cmbDelApp{0}\" > </select>", dt.Columns[col].ColumnName);
                                        break;
                                    default:
                                        break;
                                }
                            }
                        }
                    }
                    datagrid.Append("</tr>");
                }

                datagrid.Append("</table>");
                context.Response.Write(datagrid.ToString());
            }
            catch (Exception ex)
            {
                context.Response.Write("1");
                ErrorHandler.saveErrorLog(ex, CMSContext.CurrentUser.MemberName);
            }
        }



        // This method is called from CompareDuplicate Page  for remove Multiple Clients
        public void DuplicateMultipleClient(string clients, int duplicateWith, string hOperator)
        {
            bool flag = false;
            try
            {
                flag = DuplicateContactHandler.duplicateMultipleClient(clients, duplicateWith, hOperator);
                context.Response.Write(flag);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex, CMSContext.CurrentUser.MemberName);
            }
        }

    }
}